from fastapi import APIRouter, Form, Request
from tool import db
from model import Q_choice, Q_word
from data_model import Choice, Word

router = APIRouter()

@router.get("/get_qdata")
def index():
    choice = db.query(Q_choice).all()
    word = db.query(Q_word).all()
    choice.extend(word)
    db.close()
    return choice


@router.post("/insert_choice/")
async def insert_choice(choice: Choice):
    new_data = Q_choice(language=choice.language, question=choice.question, A=choice.A, B=choice.B, C=choice.C,
                        D=choice.D, answer=choice.answer, type=0)
    db.add(new_data)
    db.commit()
    db.close()
    return True


@router.post("/insert_word/")
async def insert_choice(word: Word):
    new_data = Q_word(language=word.language, question=word.question, answer=word.answer, type=1)
    db.add(new_data)
    db.commit()
    db.close()
    return True


@router.get("/{item_id}/{type}/q_item")
async def get_item(item_id: int, type: int):
    if type == 0:
        item = db.query(Q_choice).filter_by(id=item_id).first()
    else:
        item = db.query(Q_word).filter_by(id=item_id).first()
    if item:
        return item
    return False


@router.delete("/{item_id}/{type}/q_del")
async def q_del(item_id: int, type: int):
    if type == 0:
        item = db.query(Q_choice).filter_by(id=item_id).first()
    else:
        item = db.query(Q_word).filter_by(id=item_id).first()
    db.delete(item)
    db.commit()
    db.close()
    return True


@router.put("/q_put")
async def insert_choice(request: Request):
    p = await request.json()
    if p['type'] == 0:
        item = db.query(Q_choice).filter_by(id=p['id']).first()
        item.question = p['question']
        item.A = p['A']
        item.B = p['B']
        item.C = p['C']
        item.D = p['D']
        item.answer = p['answer']
    else:
        item = db.query(Q_word).filter_by(id=p['id']).first()
        item.question = p['question']
        item.answer = p['answer']
    db.commit()
    db.close()
    return True